//
//  SinaHomeViewModel.swift
//  MySinaWeiBoSwiftProject
//
//  Created by apple on 2016/11/16.
//  Copyright © 2016年 WangChen. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel
import SDWebImage

class SinaHomeViewModel: NSObject {
    
    //tableView的数据
    var statusVMList: [SinaHomeCellViewModel] = [SinaHomeCellViewModel]()
    
    
    
    // MARK:
    // MARK: - 加载数据的方法
    func loadData(isPullUp: Bool, finished:@escaping (Bool,Int)->()) {
        
        //进行网络请求
        var maxID: Int64 = 0
        var sinceID: Int64 = 0
        
        //如果是上拉
        if isPullUp {
            maxID = statusVMList.last?.statusModel?.id ?? 0
            if(maxID != 0){
                maxID = maxID - 1
            }
        }else{
            sinceID = statusVMList.first?.statusModel?.id ?? 0
        }
        
        
        SinaHomeDAL.loadHomeData(sinceId: sinceID, maxId: maxID) { (statuses) in
            
            if statuses == nil{
                finished(false,0)
                return
            }
            
            var tempArray = [SinaHomeCellViewModel]()
            for statusDict in statuses!{
                
                let status = SinaStatusModel()
                status.yy_modelSet(with: statusDict)
                let statusViewModel = SinaHomeCellViewModel()
                statusViewModel.statusModel = status
                tempArray.append(statusViewModel)
                
            }

            
            if isPullUp{
                self.statusVMList = self.statusVMList + tempArray
            }else{
                self.statusVMList = tempArray + self.statusVMList
            }
            
            //加载完毕数据,马上判断是否有单张图片,并开始下载,下载完成图片之后在进行回调
            
            self.cacheSingleImage(modelArrar: tempArray, finish: finished)
            
        }
    }
    
    
    
    func cacheSingleImage(modelArrar: [SinaHomeCellViewModel], finish: @escaping (Bool,Int)->()){
        
        if modelArrar.count == 0{
            finish(true,modelArrar.count)
            return
        }
        
        //调度组,都执行下载完毕之后在进行回调
        let group = DispatchGroup()
        for theHomeCellModel in modelArrar{
            if theHomeCellModel.imageURLs?.count == 1{
                //调度组+1
                group.enter()
                
                //得到url
                let urlStr = theHomeCellModel.statusModel?.pic_urls?.first?.wap360URLStr ?? ""
                let url = URL(string: urlStr)
                //下载图片
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (_, _, _, _, _) in
                    print("单张图片下载成功")
                    //出调度组
                    group.leave()
                })
            }
        }
        group.notify(queue: DispatchQueue.main) {
            print("所有单张图片都下载完毕")
            finish(true,modelArrar.count)
            
        }
    }
}
